package cn.bnjy.util;

import cn.bnjy.common.WeiXinConstant;
import cn.bnjy.common.EasyData;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * 描述：微信工具类
 *
 * @date: 2018/11/3 1:58
 * @author: chavin
 */
public class WXUtils {

    /**
     * 校验微信Token
     * @param signature
     * @param timeStamp
     * @param nonce
     * @return
     */
    public static boolean verifyToken(String signature, String timeStamp, String nonce) {
        // 字典排序
        String[] array = new String[]{EasyData.CONFIG_MAP.get(WeiXinConstant.TOKEN), timeStamp, nonce};
        Arrays.sort(array);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            str.append(array[i]);
        }
        try {
            // 将排序后的字符串进行SHA1加密，与signature对比，如果是一样则校验成功，否则校验失败
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            String tmpStr = byteToStr(digest);
            return signature != null && signature.equals(tmpStr);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        return new String(tempArr);
    }

}
